package com.jinxin.platform.cdzxkacs.task;

import com.jinxin.platform.cdzxkacs.bean.CdzxkacsDevice;
import com.jinxin.platform.cdzxkacs.rpc.SysUserRpc;
import com.jinxin.platform.cdzxkacs.service.IAcsDeviceService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;

/**
 * Description: bccah
 * Created by 34759 on 2019/8/16 15:57
 */
@EnableScheduling
@Configuration
@Component
@Slf4j
public class DeviceTask {
    @Autowired
    private SysUserRpc sysUserRpc;
    @Autowired
    private IAcsDeviceService acsDeviceService;
    /**
     * 定时更新设备状态 每隔30秒更新一次哦
     */
    @Scheduled(cron = "0/30 * * * * ?  ")
    public void updateDeviceStatus(){
        List<CdzxkacsDevice> list = acsDeviceService.list(new HashMap());
        for(CdzxkacsDevice device : list) {
            String serialNum = device.getSerialNum();
            int deviceStatus = sysUserRpc.getDeviceStatus(serialNum, device.getProductCode());
            String statusStr = deviceStatus == 0 ? "在线" : "未知";
            log.info("获取设备：Mac(" + device.getDeviceMac()+")的在线状态是：" + statusStr);
            device.setStatus(deviceStatus);
            acsDeviceService.saveOrUpdate(device);
        }
    }
    /**
     * 定时(每小时)重新订阅
     */
//    @Scheduled(cron = "0 0 0/1 * * ? ")
    @Scheduled(cron = "0 0/5 * * * ? ")
    public void reSubscribe(){
        List<CdzxkacsDevice> list = acsDeviceService.list(new HashMap());
        for(CdzxkacsDevice device : list) {
            String subscribeId = device.getSubscribeId();
            String serialNum = device.getSerialNum();
            String productCode = device.getProductCode();
            String deviceIp = device.getDeviceIp();
            Integer port = device.getPort();
            String id = device.getId();
            if(StringUtils.isEmpty(subscribeId)){
                sysUserRpc.createSubscription(id,serialNum,productCode,deviceIp,port);
            }else {
                boolean succeed = sysUserRpc.deleteSubscription(serialNum, productCode, subscribeId);
                if(succeed){
                    sysUserRpc.createSubscription(id,serialNum,productCode,deviceIp,port);
                }
            }

        }
    }

}
